<template>
  <BasicModal
    v-bind="$attrs"
    @register="registerModal"
    @ok="handleSubmit"
    width="1000px"
    :okText="okText"
    title="驱动配置"
    @cancel="cancel"
  >
    <Tabs
      :tabBarStyle="tabBarStyle"
      @tabClick="changeTabs"
      v-model:activeKey="activeKey"
      :class="drive_id == 0 ? 'driveconfig' : ''"
    >
      <TabPane tab="详情" key="1">
        <div class="pt-3px pr-3px">
          <BasicForm @register="registerForm" />
        </div>
      </TabPane>
      <TabPane tab="驱动" key="2"><Drive ref="sondrivesRef" /></TabPane>

      <TabPane tab="属性" key="3"
        ><Attr :protocol_type="protocol_type" :device_mode_id="device_mode_id" v-if="isreload"
      /></TabPane>
    </Tabs>
  </BasicModal>
</template>
<script lang="ts">
  import { defineComponent, ref, unref, nextTick, watch } from 'vue';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { BasicForm, useForm } from '/@/components/Form/index';
  import { Tabs, TabPane } from 'ant-design-vue';
  import { fromConfig } from './formData';
  import Drive from '../drive/index.vue';
  import Attr from './attr.vue';
  import { getUpdateDeviceMode } from '/@/api/sys/gateway/gateway';
  import Bus from '/@/utils/helper/eventbus';
  import { useMessage } from '/@/hooks/web/useMessage';
  export default defineComponent({
    components: { BasicModal, BasicForm, Tabs, TabPane, Drive, Attr },
    props: {
      formData: { type: Object },
    },
    emits: ['success', 'register'],
    setup(_, { emit }) {
      const okText = ref('确定');
      const isUpdate = ref(true);
      const targetID = ref(null);
      const isreload = ref(true);
      const { createMessage } = useMessage();
      const device_mode_id = ref(); //物模型id
      const drive_id = ref(); //物模型绑定的驱动id用户回显展示
      const sondrivesRef = ref();
      const protocol_type = ref(); //驱动类型(添加属性需要携带)
      const [registerForm, { setFieldsValue, resetFields, validate }] = useForm(fromConfig);
      const activeKey = ref();
      const [registerModal, { setModalProps, closeModal }] = useModalInner((data) => {
        resetFields();
        targetID.value = data.rowdata.id;
        data && onDataReceive(data);
      });

      function cancel() {
        emit('success', { isreload: true });
        activeKey.value = '1';
      }

      watch(activeKey, (newVal) => {
        if (newVal == 3) {
          isreload.value = false;
          nextTick(() => {
            //写入操作
            isreload.value = true;
          });
        }
      });

      //切换tabs事件
      function changeTabs(e) {
        okText.value = '确定';
        if (e == '3' || e == 3) {
          return false;
        }
        if (e == 2) {
          okText.value = '下一步';
          nextTick(() => {
            Bus.$emit('send_device_type_id', {
              device_mode_id: device_mode_id.value,
              default_drive_id: drive_id.value,
            });
          });
        } else {
          okText.value = '确定';
        }
      }

      function onDataReceive(data) {
        setModalProps({ confirmLoading: false });
        isUpdate.value = !!data?.isUpdate;
        protocol_type.value = data.rowdata.connect_type;
        drive_id.value = data.rowdata.drive_id;
        device_mode_id.value = data.rowdata.id;
        //初始化驱动
        if (unref(isUpdate)) {
          setFieldsValue(data.rowdata);
        }
      }
      //更新物模型数据
      async function updateDeviceMode(data, type) {
        getUpdateDeviceMode(data).then(() => {
          if (type == 1) {
            emit('success', { isUpdate: unref(isUpdate) });
          } else {
            createMessage.success('绑定驱动成功');
          }
        });
      }

      async function handleSubmit() {
        try {
          setModalProps({ confirmLoading: true });
          const values = await validate();
          //编辑详情和编辑驱动同一个接口
          if (activeKey.value == 1) {
            let data = Object.assign({}, values, isUpdate.value ? { id: targetID.value } : {});
            updateDeviceMode(data, 1);
          } else if (activeKey.value == 2) {
            if (sondrivesRef.value.driverInfo.id) {
              activeKey.value = '3';
              okText.value = '确定';
              let data = Object.assign({}, values, isUpdate.value ? { id: targetID.value } : {});
              data.drive_id = sondrivesRef.value.driverInfo.id
                ? sondrivesRef.value.driverInfo.id
                : null;
              drive_id.value = sondrivesRef.value.driverInfo.id;
              updateDeviceMode(data, 2);
              protocol_type.value = sondrivesRef.value.driverInfo.connect_type;
            } else {
              createMessage.warn('请选择驱动');
            }
            //更改ok按钮的文本
            return false;
          } else {
            emit('success', { isreload: true });
          }
          closeModal();
          activeKey.value = '1';
        } finally {
          setModalProps({ confirmLoading: false });
        }
      }

      return {
        isreload,
        updateDeviceMode,
        device_mode_id,
        drive_id,
        okText,
        activeKey,
        cancel,
        registerModal,
        registerForm,
        handleSubmit,
        changeTabs,
        sondrivesRef,
        protocol_type,
        tabBarStyle: {
          textAlign: 'center',
        },
      };
    },
  });
</script>
<style>
  .driveconfig .ant-tabs-tab:last-child {
    pointer-events: none;
    color: #ccc;
  }
</style>
